import { Form, Input, Button, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { setToken } from "@/store/modules/userSlice";
import { setTabsList } from "@/store/modules/tabsSlice";
import { Login as LoginInterface } from "@/api/interface";
import { loginApi } from "@/api/modules/login";
import "./login.scss";

const IPT_RULE_USERNAME = [
	{
		required: true,
		message: "请输入用户名"
	}
];

const IPT_RULE_PASSWORD = [
	{
		required: true,
		message: "请输入密码"
	}
];

const Login = () => {
	const dispatch = useDispatch();
	const navigate = useNavigate();

	// 登陆
	const onFinish = async (loginForm: LoginInterface.ReqLoginForm) => {
		try {
			const { data } = await loginApi(loginForm);
			dispatch(setToken(data!.token));
			dispatch(setTabsList([]));
			message.success("登录成功！");
			navigate("/home/index");
		} catch (e) {
			console.log(e);
		}
	};

	return (
		<div className="login-container">
			<div className="wrapper">
				<div className="title">react-ant-admin</div>
				<div className="welcome">欢迎使用，请先登录</div>
				<Form className="loginForm" initialValues={{ remember: true }} onFinish={onFinish} size="large">
					<Form.Item name="username" rules={IPT_RULE_USERNAME}>
						<Input placeholder="账号:admin" prefix={<UserOutlined />} />
					</Form.Item>
					<Form.Item name="password" rules={IPT_RULE_PASSWORD}>
						<Input type="password" placeholder="密码:123456" prefix={<LockOutlined />} />
					</Form.Item>
					<Form.Item className="login-btn">
						<Button type="primary" htmlType="submit">
							登录
						</Button>
						<Button htmlType="reset">重置</Button>
					</Form.Item>
				</Form>
			</div>
		</div>
	);
};

export default Login;
